package top.xcxdl.rural.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import top.xcxdl.rural.entity.RuralUser;
import top.xcxdl.rural.mapper.RuralUserMapper;
import top.xcxdl.rural.service.IRuralUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.xcxdl.rural.utils.ImageAddress;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-05-05
 */
@Service
public class RuralUserServiceImpl extends ServiceImpl<RuralUserMapper, RuralUser> implements IRuralUserService {

    @Override
    public PageInfo<RuralUser> getList(Integer pageNo, Integer pageSize, String key) {
        PageHelper.startPage(pageNo, pageSize);
        List<RuralUser> list = baseMapper.getList(key);
        // 将图片地址替换为绝对地址
        list.forEach(ruralUser -> {
           ruralUser.setUserAvatarUrl(ImageAddress.getAllPath(ruralUser.getUserAvatarUrl()));
        });
        return new PageInfo<>(list);
    }

    @Override
    public boolean changeStatus(RuralUser user) {
        return updateById(user);
    }

    @Override
    public int doDelete(List<Integer> ids) {
        QueryWrapper<RuralUser> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", ids);
        return baseMapper.delete(wrapper);
    }

    @Override
    public RuralUser getUserByOpenId(String openid) {
        QueryWrapper<RuralUser> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_openid", openid);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public int toInsertUser(RuralUser user) {
        user.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000));
        user.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
        return baseMapper.insert(user);
    }

    @Override
    public void toUpdateUser(RuralUser user) {
        user.setUpdateTime(String.valueOf(System.currentTimeMillis() / 1000));
        baseMapper.updateById(user);
    }

    @Override
    public List<RuralUser> getFriendListById(Integer loginUserId) {
        List<RuralUser> list = baseMapper.getFreindListById(loginUserId);
        list.forEach(ruralUser -> {
            ruralUser.setUserAvatarUrl(ImageAddress.getAllPath(ruralUser.getUserAvatarUrl()));
        });
        return list;
    }

    @Override
    public RuralUser getUserById(Integer id) {
        RuralUser user = baseMapper.getUserById(id);
        if (user != null) {
            user.setUserAvatarUrl(ImageAddress.getAllPath(user.getUserAvatarUrl()));
        }
        return user;
    }
}
